import 'package:shared_preferences/shared_preferences.dart';

/// create by SunJH on 2021/11/30
/// contact me by email 965989158@qq.com
/// 说明: 本地数据存储工具

class LocalStorage {
  SharedPreferences? _sp;

  LocalStorage._pre(this._sp);

  LocalStorage._();

  static LocalStorage? _instance;

  static LocalStorage getInstance() => _instance ??= LocalStorage._();

  //预初始化，防止get时，SharedPreferences还未初始化完毕
  static Future<LocalStorage> preInit() async {
    if (_instance == null) {
      var preferences = await SharedPreferences.getInstance();
      _instance = LocalStorage._pre(preferences);
    }
    return _instance!;
  }

  Future<bool> remove(String key) async {
    if(_sp == null) throw Exception("please call preInit");
    return _sp!.remove(key);
  }

  set(String key, Object value) async {
    if(_sp == null) throw Exception("please call preInit");
    if (value is int) {
      _sp!.setInt(key, value);
    } else if (value is String) {
      _sp!.setString(key, value);
    } else if (value is double) {
      _sp!.setDouble(key, value);
    } else if (value is bool) {
      _sp!.setBool(key, value);
    } else {
      throw Exception("only Support int、String、double、bool");
    }
  }

  T? get<T>(String key) {
    if(_sp == null) throw Exception("please call preInit");
    var object = _sp!.get(key);
    switch (object.runtimeType) {
      case int:
        return object as T;
      case bool:
        return object as T;
      case String:
        return object as T;
      case Null:
        return null;
      default:
        throw Exception('''only Support int、String、double、bool''');
    }
  }
}
